/**
 * 解析url参数
 * Created by yi on 2016-12-28.
 * @return Object {id:12334}
 */
export function urlParse(variable) {
  let url = window.location.search.substr(1);
  var vars = url.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    console.log(vars)
    if (pair[0] == variable) {
      return +pair[1];
    }else{

    }
    return 4;
  }
};

const card_types = [
  {
    name: 'American Express',
    code: 'ax',
    pattern: /^3[47]/,
    valid_length: [15],
    formats : [
      {
        length: 15,
        format: 'xxxx xxxxxxx xxxx'
      }
    ]
  }, {
    name: 'Diners Club',
    code: 'dc',
    pattern: /^3[68]/,
    valid_length: [14],
    formats : [
      {
        length: 14,
        format: 'xxxx xxxx xxxx xx'
      }
    ]
  }, {
    name: 'JCB',
    code: 'jc',
    pattern: /^35/,
    valid_length: [16],
    formats : [
      {
        length: 16,
        format: 'xxxx xxxx xxxx xxxx'
      }
    ]
  }, {
    name: 'Visa',
    code: 'vs',
    pattern: /^4/,
    valid_length: [16],
    formats : [
      {
        length: 16,
        format: 'xxxx xxxx xxxx xxxx'
      }
    ]
  }, {
    name: 'Mastercard',
    code: 'mc',
    pattern: /^5[1-5]/,
    valid_length: [16],
    formats : [
      {
        length: 16,
        format: 'xxxx xxxx xxxx xxxx'
      }
    ]
  }
];

export function ccFormat(ccCode){
  let card_type = getCardType(ccCode)
  return formatCardNumber(ccCode,card_type)
}

// function isValidLength(ccCode,card_type){
//   if(ccCode.length <= card_type.valid_length){

//   }
// }

function getCardType(ccCode){
  let i;
  for(i=0;i<card_types.length;i++){
    let card_type = card_types[i]
    if(ccCode.match(card_type.pattern)){
      return card_type
    }
  }
}

function getCardFormatString(ccCode,card_type){
  let i
  for(i=0;i<card_type.formats.length;i++){
    let format = card_type.formats[i]
    if(ccCode.length <= format.length){
      return format.format
    }
  }
}

function formatCardNumber(ccCode,card_type){
  let numAppendedChars = 0;
  let formattedNumber = ''
  let cardFormatString = getCardFormatString(ccCode,card_type)
  // debugger
  let i
  for(i=0;i<ccCode.length;i++){
   let cardFormatIndex = i + numAppendedChars;

    if (cardFormatString.charAt(cardFormatIndex) !== 'x') {
      numAppendedChars++;
      formattedNumber += cardFormatString.charAt(cardFormatIndex) + ccCode.charAt(i);
    } else {
      formattedNumber += ccCode.charAt(i);
    }
  }
  return formattedNumber;
}


export function verifyCardNumber(ccCode){
  let i;
  for(i=0;i<card_types.length;i++){
    let card_type = card_types[i]
    if(ccCode.match(card_type.pattern) && ccCode.length === card_type.valid_length[0]){
      return true
    }
  }
  return false

}
